#!/usr/bin/env python
import commands, time, re
import os

number_re = "+([0-9]+\.[01-9]+|[0-9]+)"

def drop_caches():
  number_re = " +([0-9]+\.[0-9]+|[0-9]+)"
  before = commands.getoutput('cat /proc/meminfo')
  mem_total = re.findall("MemTotal:"+number_re, before)[0]
  before_cached = re.findall("Cached:"+number_re, before)[0]
  before_free = re.findall("MemFree:"+number_re, before)[0]
  commands.getoutput('echo 3 | sudo tee /proc/sys/vm/drop_caches')
  after = commands.getoutput('cat /proc/meminfo')
  after_cached = re.findall("Cached:"+number_re, after)[0]
  after_free = re.findall("MemFree:"+number_re, after)[0]
  print 'drop caches.'
  print 'MemTotal:', mem_total,'kB'
  print 'before MemFree:', before_free,'kB','before Cached:', before_cached,'kB'
  print 'after MemFree:', after_free,'kB','after Cached:', after_cached,'kB'

def get_synchronization_overhead(log):
  try:
    #return re.findall('Elasped time : '+number_re, log)[0]
    val = re.findall('Total Elapsed Time : '+number_re, log)[0]
    return val
  except:
    return '-'

def get_synchronization_latency(log):
  try:
    val = re.findall('thread0 latency: '+number_re, log)[0]
    return val
  except:
    return '-'

def get_failures(log):
  try:
    val = re.findall('Total Failures : '+number_re, log)[0]
    return val
  except:
    return '-'

for version in ['0','1','2','3','4','5','6']:
#for version in ['0']:
  if version is '0':
    fname = 'CTransactionalMemory'
  elif version is '1':
    fname = 'CCoarseGrainedLockStack'
  elif version is '2':
    fname = 'CLockFreeStack'
  elif version is '3':
    fname = 'CEliminationBackoffStack'
  elif version is '4':
    fname = 'CCoarseGrainedTransactionalMemory'
  elif version is '5':
    fname = 'CLockFreeTransactionalMemory'
  elif version is '6':
    fname = 'CEliminationBackoffTransactionalMemory'

  log = open('./log/'+fname+'.csv', 'w+')
  for operations in ['10000','50000','100000']:
    log.write('operations,'+operations+',pushRatio,0.75')
    log.write('\n')
    for pushRatio in ['0.75']:
      log.write('participants,overhead,latency\n')
      for participants in ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24']:
        cmd = './test_stack '+version+' '+participants+' '+pushRatio+' '+operations+' '+'1000'
        drop_caches()
        output = commands.getoutput(cmd)
        print output
        overhead = get_synchronization_overhead(output)
        latency = get_synchronization_latency(output)
        failures = get_failures(output)

        log.write(participants+','+overhead+','+latency+','+failures+'\n')
  log.close()

